import 'dart:async';
import 'dart:io';
import 'dart:typed_data';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_sound/flutter_sound.dart' hide RecorderPlaybackController, SoundPlayerUI,SoundRecorderUI ;
import 'package:intl/date_symbol_data_local.dart';

import 'package:path_provider/path_provider.dart' show getTemporaryDirectory;
import 'package:permission_handler/permission_handler.dart';
import 'package:studymanage/core/sound/ui/demo_active_codec.dart';
import 'package:studymanage/core/sound/ui/recorder_playback_controller.dart';
import 'package:studymanage/core/sound/ui/recorder_state.dart';
import 'package:studymanage/core/sound/ui/remote_player.dart';
import 'package:studymanage/core/sound/ui/sound_player_ui.dart';
import 'package:studymanage/core/sound/ui/sound_recorder_ui.dart';
import 'package:studymanage/core/sound/util/temp_file.dart';
import 'package:studymanage/util/request.dart';

class ToRemark extends StatefulWidget {
  final Map id;
  final update;
  ToRemark(this.id,this.update);

  @override
  State<StatefulWidget> createState() {
    return ToRemarkState();
  }
}

class ToRemarkState extends State<ToRemark>{
  final GlobalKey<FormState> _formKey = new GlobalKey<FormState>();
  String filepath=""; //录音本地路径
  String content=""; //分享内容
  Map _course ={};

  int _audioDuration = 1;
  double _currentSchedule = 0.0; // 进度条当前的值（0 ~ 1）
  Timer _timer; // 播放计时器
  bool soundIng=false;
  bool initialized = false;
  Track track;

  Future<bool> init()  async {
    if (!initialized) {
      initializeDateFormatting();
      await UtilRecorder().init();
      ActiveCodec().recorderModule = UtilRecorder().recorderModule;
      ActiveCodec().setCodec(withUI: false, codec: Codec.aacADTS);

      initialized = true;
    }
    return initialized;
  }

  @override
  void initState() {
    super.initState();
    setState(() {
      _course = widget.id;
    });
    Future<PermissionStatus> status =  Permission.microphone.request();
    status.then((stat) {
      if (stat != PermissionStatus.granted) {
        throw RecordingPermissionException("Microphone permission not granted");
      }
    });
    tempFile(suffix: '.aac').then((path){
      filepath = path;
      track = Track(trackPath: filepath);
      setState(() {
      });
    });
    init();

  }

  @override
  void dispose() {
    if (_timer != null) {
      _timer.cancel();
      _timer = null;
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: Text('课程点评',
          style: TextStyle(
            fontFamily: 'PingFangSC-Medium',
            fontSize: ScreenUtil().setSp(16),
            fontWeight: FontWeight.w600,
            color: Color.fromRGBO(51, 51, 51, 1),
            height: 1,
          ),
        ),
        centerTitle: true,
        backgroundColor: Colors.transparent,
        elevation: 0,
        leading: FlatButton(
          child: Icon(
            Icons.navigate_before,
            color: Color.fromRGBO(51, 51, 51, 1),
          ),
          onPressed: () {
            Navigator.pop(context);
          },
        ),
        actions: <Widget>[
          Container(
            width: ScreenUtil().setWidth(90),
            child: FlatButton(
              padding: EdgeInsets.only(
                left: ScreenUtil().setWidth(15.5),
                right: ScreenUtil().setWidth(15.5),
              ),
              child: Text('确认提交',
                style: TextStyle(
                  fontFamily: 'PingFangSC-Regular',
                  fontSize: ScreenUtil().setSp(13),
                  color: Color.fromRGBO(51, 51, 51, 1),
                  height: 1,
                ),
              ),
              onPressed: () => _remark(),
            ),
          ),
        ],
      ),
      body: GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () {
          // 触摸收起键盘
          FocusScope.of(context).requestFocus(FocusNode());
        },
        child: SingleChildScrollView(
          child: Form(
            key: _formKey,
            child: Container(
              width: MediaQuery.of(context).size.width,
              padding: EdgeInsets.only(
                left: ScreenUtil().setWidth(15),
                right: ScreenUtil().setWidth(15),
                top: ScreenUtil().setHeight(22),
              ),
              decoration: BoxDecoration(
                border: Border(
                  top: BorderSide(
                    color: Color.fromRGBO(248, 248, 248, 1),
                    width: ScreenUtil().setHeight(7.5),
                  ),
                ),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Container(
                    margin: EdgeInsets.only(top:10),
                    color: Colors.white,
                    child: Column(
                      children: <Widget>[
                        Container(
                          padding: EdgeInsets.all(13),
                          decoration: BoxDecoration(
                              color: Color(0xffF8F8F8),
                              borderRadius: BorderRadius.circular(4)
                          ),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              Row(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: <Widget>[
                                  Container(
                                    height: 41,
                                    width: 41,
                                    child: CircleAvatar(
                                      backgroundImage: NetworkImage(_course['studentAvatar']),
                                      radius: ScreenUtil().setWidth(20.5),
                                    ),
                                  ),
                                  Expanded(
                                    child: Container(
                                      margin: EdgeInsets.only(left: 10),
                                      child: Column(
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        children: <Widget>[
                                          Row(
                                            children: <Widget>[
                                              Text(
                                                _course['studentNickname'],
                                                style: TextStyle(
                                                  fontFamily: 'PingFangSC-Medium',
                                                  fontSize: ScreenUtil().setSp(14),
                                                  fontWeight: FontWeight.w600,
                                                  color: Color.fromRGBO(51, 51, 51, 1),
                                                  height: 1,
                                                ),
                                              ),
                                              Offstage(
                                                offstage: _course['className']==null,
                                                child: Container(
                                                  alignment: Alignment.center,
                                                  width: 50,
                                                  padding: EdgeInsets.all(3),
                                                  margin: EdgeInsets.only(
                                                    left: 3,
                                                  ),
                                                  decoration: BoxDecoration(
                                                    border: Border.all(
                                                      color: Color.fromRGBO(133, 133, 133, 1),
                                                      width: ScreenUtil().setHeight(0.5),
                                                    ),
                                                    borderRadius: BorderRadius.all(
                                                      Radius.circular(ScreenUtil().setHeight(2)),
                                                    ),
                                                  ),
                                                  child: Text(
                                                    _course['className']!=null? _course['className'] : "暂无",
                                                    overflow: TextOverflow.ellipsis,
                                                    style: TextStyle(
                                                      fontFamily: 'PingFangSC-Light',
                                                      fontSize: ScreenUtil().setSp(10),
                                                      fontWeight: FontWeight.w300,
                                                      color: Color.fromRGBO(133, 133, 133, 1),
                                                    ),
                                                  ),
                                                ),
                                              ),
                                              Offstage(
                                                offstage: !_course['boolComplete'],
                                                child: Container(
                                                  padding: EdgeInsets.all(3),
                                                  margin: EdgeInsets.only(
                                                    left: 3,
                                                  ),
                                                  decoration: BoxDecoration(
                                                    border: Border.all(
                                                      color: Color.fromRGBO(133, 133, 133, 1),
                                                      width: ScreenUtil().setHeight(0.5),
                                                    ),
                                                    borderRadius: BorderRadius.all(
                                                      Radius.circular(ScreenUtil().setHeight(2)),
                                                    ),
                                                  ),
                                                  child: Text(
                                                    "已经结业",
                                                    style: TextStyle(
                                                      fontFamily: 'PingFangSC-Light',
                                                      fontSize: ScreenUtil().setSp(10),
                                                      fontWeight: FontWeight.w300,
                                                      color: Color.fromRGBO(133, 133, 133, 1),
                                                    ),
                                                  ),
                                                ),
                                              ),
                                            ],
                                          ),
                                          Container(
                                            margin: EdgeInsets.only(top: 5),
                                            child: Row(
                                              children: <Widget>[
                                                Container(
                                                  child: Text(
                                                    _course['shareDateCN'],
                                                    style: TextStyle(
                                                      fontFamily: 'PingFangSC-Light',
                                                      fontSize: ScreenUtil().setSp(11),
                                                      fontWeight: FontWeight.w300,
                                                      color: Color.fromRGBO(133, 133, 133, 1),
                                                      height: 1,
                                                    ),
                                                  ),
                                                ),
                                                Offstage(
                                                  offstage: _course.containsKey("shareRecordContentVoice")!=null,
                                                  child: RemotePlayer(_course['shareRecordContentVoice'],2),
                                                )
                                              ],
                                            ),
                                          )
                                        ],
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                              Container(
                                margin: EdgeInsets.only(left: 51,top: 10),
                                child: Text(_course['shareRecordContent']),
                              )

                            ],
                          ),
                        )
                      ],
                    ),
                  ),
                  Container(
                    height: ScreenUtil().setHeight(142),
                    margin: EdgeInsets.only(
                      top: ScreenUtil().setHeight(25),
                    ),
                    padding: EdgeInsets.only(
                      left: ScreenUtil().setWidth(15.5),
                      right: ScreenUtil().setWidth(15.5),
                    ),
                    decoration: BoxDecoration(
                      color: Color.fromRGBO(248, 248, 248, 1),
                      borderRadius: BorderRadius.all(
                        Radius.circular(ScreenUtil().setHeight(4)),
                      ),
                    ),
                    child: TextFormField(
                      maxLines: 7,
                      inputFormatters:<TextInputFormatter>[
                        LengthLimitingTextInputFormatter(100)
                      ],
                      decoration: InputDecoration(
                        border: InputBorder.none,
                        hintText: '请输入课程内容（限100字）',
                        hintStyle: TextStyle(
                          fontFamily: 'PingFangSC-Light',
                          fontSize: ScreenUtil().setSp(13),
                          fontWeight: FontWeight.w300,
                          color: Color.fromRGBO(133, 133, 133, 1),
                        ),
                      ),
                      onSaved: (v){
                        setState(() {
                          content = v;
                        });
                      },
                    ),
                  ),
                  FutureBuilder(
                    initialData: false,
                    future: init(),
                    builder: (c,d){
                      if (d.data == false) {
                        return Container(
                          width: 0,
                          height: 0,
                          color: Colors.white,
                        );
                      } else {
                        return RecorderPlaybackController(
                            child: Column(
                              children: [
                                Container(
                                  margin: EdgeInsets.only(
                                    bottom: ScreenUtil().setHeight(10),
                                  ),
                                  decoration: BoxDecoration(
                                    border: Border.all(
                                      color: Color.fromRGBO(214, 178, 128, 1),
                                      width: ScreenUtil().setHeight(1),
                                    ),
                                    borderRadius: BorderRadius.all(
                                      Radius.circular(5),
                                    ),
                                  ),
                                  child: SoundPlayerUI.fromTrack(
                                    track,
                                    type: 1,
                                    backgroundColor: Colors.white,
                                    enabled: false,
                                    showTitle: true,
                                    audioFocus: true
                                        ? AudioFocus.requestFocusAndDuckOthers
                                        : AudioFocus.requestFocusAndDuckOthers,
                                  ),
                                ),
                                SoundRecorderUI(
                                  track,
                                  onStopped: (RecordedAudio audio) {
                                    setState(() {
                                      track = audio.track;
                                    });
                                  },
                                ),
                              ],
                            ));
                      }
                    },
                  )
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  _remark() async{
    _formKey.currentState.save();
    if(content.isEmpty){
      Request().toast("请填写内容");
      return;
    }
    print('确认提交');
    if(filepath.isNotEmpty){
      Upload().upload("/multiapi/open/upload",
          FormData.fromMap({
            "file": await MultipartFile.fromFile(filepath)
          })).then((response){
        Request().post<Map<String,dynamic>>("/multiapi/c196c_studyRecord",
            data:{
              "id":  widget.id['id'],
              "teacherContent":content,
              "teacherContentVoice":response.data["url"],
              "teacherVoiceAudioDuration": _audioDuration
            }).then((response){
          widget.update();
          Navigator.pop(context);
        });
      });
    }else{
      Request().post<Map<String,dynamic>>("/multiapi/c196c_studyRecord",
          data: {
            "id":  widget.id["id"],
            "teacherContent":content,
            "teacherContentVoice":"",
            "teacherVoiceAudioDuration":0
          }).then((response){
        widget.update();
        Navigator.pop(context);
        Request().toast( '分享成功');
      });
    }
  }
  _left() {
    if(_currentSchedule < 1){
      return ScreenUtil().setWidth(155) * _currentSchedule;
    }else{
      return ScreenUtil().setWidth(165);
    }
  }
}